package org.asiainfo.common.mybatis.stream.factory;

import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.audit.AuditMessage;
import com.mybatisflex.core.audit.MessageFactory;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.asiainfo.common.core.constant.Constants;
import org.asiainfo.common.core.utils.ServletUtils;
import org.asiainfo.common.core.utils.ip.IPUtils;
import org.asiainfo.common.mybatis.stream.config.AppConfiguration;
import org.asiainfo.common.satoken.utils.LoginHelper;
import org.asiainfo.system.api.model.LoginUser;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 自定义 SQL 审计内容
 *
 * @author dotor-ww
 */
@Component
@RequiredArgsConstructor
public class MybatisFlexMessageFactory implements MessageFactory {

    private final AppConfiguration appConfiguration;

    /**
     * 创建审计详细消息
     *
     * @return 审计详细消息
     */
    @Override
    public AuditMessage create() {
        return handleAuditMessage();
    }

    /**
     * 处理审计消息
     *
     * @return 审计消息
     */
    private AuditMessage handleAuditMessage() {
        AuditMessage auditMessage = new AuditMessage();
        auditMessage.setPlatform(Constants.PLAT_FORM);
        // 应用模块
        auditMessage.setModule(appConfiguration.getApplicationName());
        // 请求路径
        HttpServletRequest request = ServletUtils.getRequest();
        String url = "";
        String ip = "";
        if (ObjectUtil.isNotNull(request)) {
            url = request.getRequestURL().toString();
            ip = IPUtils.getIpAddr();
        }
        auditMessage.setUrl(url);
        // 执行SQL的服务器IP
        auditMessage.setHostIp(IPUtils.getHostIp());
        // 请求的用户IP
        auditMessage.setUserIp(ip);
        // 用户信息基于Sa-Token实现
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (ObjectUtil.isNull(loginUser)) {
            return auditMessage;
        }
        auditMessage.setUser(loginUser.getUsername());
        // 其他元素及用户信息
        Map<String, Object> metas = Map.of("userName", loginUser.getUsername(), "userId", loginUser.getUserId());
        auditMessage.setMetas(metas);
        return auditMessage;
    }
}
